<template>
	<view class="container">
		<u-sticky :offset-top="navbarHeight">
			<view class="sticky_container">
				<view class="date">
					<view class="now-date" v-if="nowMonth.length > 0">
						<span class="f44 bold">{{ nowDay }}</span>
						<span class="f32 bold ml10">{{ nowMonth }}月</span>
					</view>
					<view class="select-date" @click="handleSelectDate" v-if="nowYear.length > 0">
						<div class="f32 bold">{{ nowYear }}</div>
					</view>
				</view>
			</view>
		</u-sticky>

		<view v-for="(item, index) in dataList" class="data-list" :key="index" :data-time="item.createTime">

			<rf-evalCell :data="item" @showAll="openShowAll" @del="handleDelete(item.id, index)"
				@edit="handleEditObserve"></rf-evalCell>
		</view>
		<!-- 删除确认弹窗 -->
		<rf-alert :show="confirmShow" @close="confirmShow=false" @confirm="confirm" title="提示"
			desc="确认删除该评价?"></rf-alert>
		<!-- 筛选时间 -->
		<u-datetime-picker ref="myElement" :show="selectDateShow" v-model="dateDaya" mode="year-month"
			confirmColor="#58C866" @cancel="selectDateShow = false" title="选择发表日期" v-on:confirm="confirmDate"
			v-on:change="changeDate"></u-datetime-picker>
	</view>
</template>

<script>
	import {
		getEvaluateList,
		deleteEvaluate,
	} from "@/api/eval.js"

	import {
		zip,
		Observable,
		Subject,
		from,
	} from 'rxjs'
	import {
		distinctUntilChanged,
		map
	} from 'rxjs/operators';
	// 创建两个主题
	const confirmSub = new Subject();
	const changeSub = new Subject();

	export default {
		name: "view-evaluate",
		data() {
			return {

				dataList: [],

				nowMonth: '',
				nowDay: '',
				nowYear: '',


				params: {
					pageSize: 10,
					pageNum: 1,
					year: '',
					month: ''
				},

				total: 0,
				status: "",

				confirmShow: false,
				selectDateShow: false,
				dateDaya: Number(new Date()),

				delId: "",
				delIndex: "",

				is_load: true, // 在数据量较少的情况下，删除会触发 onReachBottom
			};
		},
		computed: {
			navbarHeight() {
				// 90 来自 tab 高度。 upx2px ：转化为px
				return parseInt(this.navBarHeight, 10) + uni.upx2px(90) + 'px';
			}
		},
		created() {

			let that = this
			zip(confirmSub, changeSub).subscribe(([val1, val2]) => {

				that.params.year = uni.$u.timeFormat(val2.value, 'yyyy')
				that.params.month = uni.$u.timeFormat(val2.value, 'mm')

				that.nowMonth = that.params.month;
				that.nowYear = that.params.year;

				that.params.pageNum = 1

				// 
				this._getEvaluateList()
				console.log("------1------");

			});

		},
		methods: {
			formatArray(arr) {
				return arr.map(item => {
					// {{item.startTime}}-{{item.endTime}}
					item.startTime = this.formatDate(item.startTime)
					item.endTime = this.formatDate(item.endTime)
					return item
				})
			},
			formatDate(dataStr) {
				var date = new Date(dataStr);

				if (!isNaN(date)) {
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					const seconds = String(date.getSeconds()).padStart(2, '0');
					return `${year}年${month}月${day}日`;
					// return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
				} else {
					console.log("===============dataStrdataStr================" + date);
					// 无法解析日期，返回原始字符串或抛出错误，取决于需求
					return dataStr;
				}
			},
			refreshUI() {
				let _that = this
				if (_that.dataList.length > 0) {
					const query = uni.createSelectorQuery().in(_that);
					query.selectAll('.data-list').boundingClientRect(data => {
						let temp = data[0].dataset.time.split(' ')[0].split('-')
						_that.nowDay = temp[2]
						_that.nowMonth = temp[1]
						_that.nowYear = temp[0]
					}).exec();
				}
			},
			_getEvaluateList() {
				let _that = this;
				console.log("_getEvaluateList");
				getEvaluateList(this.params).then(res => {
					console.log(JSON.stringify(res));

					if (res.data.code == 200) {

						var list = res.data.rows ? res.data.rows : []
						console.log("_that.dataList", res);
						_that.total = res.data.total
						if (_that.params.pageNum == 1) {
							_that.dataList = _that.formatArray(list)
							setTimeout(() => {
								_that.refreshUI()
							}, 50)
						} else {
							_that.dataList = _that.dataList.concat(_that.formatArray(list))
						}

						console.log(_that.params.pageSize);
						if (list.length < _that.params.pageSize) {
							_that.status = 'noMore';
						} else {
							console.log("-------------------");
							_that.status = 'more';
						}
					}
				})
			},
			handleSelectDate() {
				console.log("------------------");
				this.selectDateShow = true;
			},
			// 选定日期， 筛选观察
			confirmDate(e) {
				confirmSub.next(e)
				this.selectDateShow = false;
			},
			changeDate(e) {
				changeSub.next(e)
			},

			// 删除观察
			handleDelete(id, idx) {
				let _that = this
				console.log(id, idx);
				this.delId = id;
				this.delIndex = idx;
				this.confirmShow = true
			},
			// 删除
			confirm() {
				console.log(this.delId, this.delIndex);
				let _that = this
				deleteEvaluate(this.delId).then(res => {
					console.log(res);
					console.log("res: " + JSON.stringify(res));
					if (res.code == 200) {
						_that.is_load = false
						_that.dataList.splice(_that.delIndex, 1)
						_that.confirmShow = false;
						_that._getEvaluateList();
						console.log("------2------");
					}
				}).catch(err => {

				})
			},
			handleEditObserve(item) {
				console.log("itemitem: " + JSON.stringify(item));
				uni.navigateTo({
					url: '/pages-sub/addEval/addEval?type=update&item=' + encodeURIComponent(JSON.stringify(item))
				})

			},
			// 初始化日期
			initTime() {
				const time = new Date();
				//获得系统年份;
				const year = time.getFullYear();
				//获得系统月份;
				const month = time.getMonth() + 1;
				//获得系统当月分天数;
				const day = time.getDate();
				//获得系统星期几;
				let dayCycle = time.getDay();
				//使用数组更改日期样式;
				const dayCycleArray = ["日", "一", "二", "三", "四", "五", "六"];
				for (let i = 0; i < 7; i++) {
					if (dayCycle == i) {
						//将dayCycleArray的数赋值到系统星期几里面中去;
						dayCycle = dayCycleArray[i];
					}
				}
				this.dateStr = year + '/' + month + '/' + day + ' ';
				this.week = '星期' + dayCycle;

				// this.nowMonth = month;
				// this.nowDay = day;
				// this.nowYear = year;
			},
		},
		mounted() {
			this.initTime();
			let _that = this;

			_that.params.pageNum = 1;
			_that._getEvaluateList()

			uni.$on('onPageScroll', function(data) {
				if (_that.dataList.length > 0) {
					const query = uni.createSelectorQuery().in(_that);
					query.selectAll('.data-list').boundingClientRect(data => {
						for (let index = 0; index < data.length; index++) {
							if (data[index].top > 190 && data[index].top < 300) {
								let temp = data[index].dataset.time.split(' ')[0].split('-')
								_that.nowDay = temp[2]
								_that.nowMonth = temp[1]
								_that.nowYear = temp[0]
								break
							};
						}
					}).exec();

				}

			});

			uni.$on('onReachBottom', function() {

				if (_that.is_load == false) {
					_that.is_load = true
					return
				}


				if (_that.dataList.length >= _that.total) {
					_that.status = 'noMore';
				} else {
					_that.status = 'more';
					_that.params.pageNum++
					_that._getEvaluateList()
					console.log("------4------");
				}

			});
			uni.$on('RefreshEvalList', function() {
				// 创建或者编辑学期评价后刷新
				_that.params.pageNum = 1;
				_that._getEvaluateList()
			});


			// //  设置 top 时间，显示最新一条信息的时间
			// setTimeout(() => {
			// 	if (_that.dataList.length > 0) {
			// 		const query = uni.createSelectorQuery().in(_that);
			// 		query.selectAll('.data-list').boundingClientRect(data => {
			// 			let temp = data[0].dataset.time.split(' ')[0].split('-')
			// 			_that.nowDay = temp[2]
			// 			_that.nowMonth = temp[1]
			// 			_that.nowYear = temp[0]
			// 		}).exec();
			// 	}
			// }, 1000)

		},
		beforeDestroy() {
			uni.$off('onPageScroll')
			uni.$off('onReachBottom')
			uni.$off('RefreshEvalList')
		}
	}
</script>


<style lang="scss" scoped>
	.container {
		background-color: white;

		.sticky_container {
			padding: 0 0;
			background-color: white;
			border-radius: 0 0 0 0;

			.date {
				background-color: #fff;
				height: 80rpx;
				padding: 0 32rpx;
				display: flex;
				justify-content: space-between;
				align-items: flex-end;

				.now-date {
					// margin-top: 32rpx;
					// flex: 1;
				}

				.select-date {
					// margin-top: 32rpx;
					position: relative;
					padding-right: 45rpx;
					// flex: 1;

					&:before {
						content: '';
						width: 0;
						height: 0;
						position: absolute;
						right: 0;
						top: 15rpx;
						border-top: 15rpx solid #3A3D4B;
						border-left: 15rpx solid transparent;
						border-right: 15rpx solid transparent;
					}
				}
			}
		}

		.data-list {}



	}
</style>